package com.learn.im.controller;

import ch.qos.logback.core.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author Emp
 * @version :    1.0
 */
@Controller
@RequestMapping("download")
@Slf4j
public class DownloadController {

    // 文件保存路径
    @Value("${im.storage.path}")
    private String FILE_PATH;

    /**
     * 文件的下载接口
     */
    @RequestMapping("file")
    public void downWebSocketFile(String filePath, HttpServletResponse response) {
        File file = new File(FILE_PATH + filePath);
        log.info("文件下载路径:{}",FILE_PATH + filePath);
        log.info("文件是否存在:{}",file.exists());
        log.info("文件名:{}",file.getName());
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
             OutputStream os = response.getOutputStream()){
            // 设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(), "UTF-8"));
//            response.setHeader("Transfer-Encoding", "chunked"); 这个响应头会让浏览器无法下载小文件?
            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer)) > 0){
                os.write(buffer,0,len);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 图片的流数据接口
     */
    @RequestMapping("img")
    public void downImg(String filePath, HttpServletResponse response) {
        File file = new File(FILE_PATH + filePath);
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
             OutputStream os = response.getOutputStream()){
            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer)) > 0){
                os.write(buffer,0,len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
